import { ref, computed } from 'vue'
import { useMessageManager } from './useMessageManager'
import { useUserStore } from '../../auth/stores/user' 
/**
 * 流式处理核心
 */
export interface StreamParams {
  message: string
  images?: string[]
  documents?: string[]  // 文档base64数组
  model: number
  mcpEnabled: boolean
  memoryEnabled: boolean
  knowledgeId?: number
  systemPrompt?: string
  systemPromptId?: number  // 系统提示词模板ID
  useTools: boolean
}

export interface StreamCallbacks {
  onStart?: () => void
  onOpen?: () => void
  onProgress?: (text: string, status: string) => void
  onComplete?: () => void
  onError?: (error: Error) => void
}

export function useChatStream() {
  const { messages, addMessage, updateMessage } = useMessageManager()
  const userStore = useUserStore()
  
  const isStreaming = ref(false)
  const abortController = ref<AbortController | null>(null)
  const globalStreamId = ref(0)
  const currentStreamId = ref(0)
  
  const thinkingMessages = ref<string[]>([])
  const showThinking = ref(false)
  const thinkingContent = computed(() => thinkingMessages.value.join(''))
  
  const aiState = ref<'idle' | 'waiting' | 'thinking' | 'answering'>('idle')
  
  const hasMeaningfulContent = (text: string): boolean => {
    if (!text) return false
    const meaningfulPattern = /[\p{L}\p{N}]/u
    return meaningfulPattern.test(text)
  }
  
  const sendStreamMessage = async (
    params: StreamParams & { skipContentIndexGeneration?: boolean, contentIndex?: number, isEdit?: boolean },
    callbacks?: {
      onStart?: () => void
      onOpen?: () => void
      onProgress?: (text: string, status: string) => void
      onError?: (error: Error) => void
      onComplete?: () => void
    }
  ) => {
    if (isStreaming.value) {
      throw new Error('AI回复中，请勿重复发送')
    }
    
    // 重置状态
    thinkingMessages.value = []
    showThinking.value = false
    isStreaming.value = true
    aiState.value = 'waiting'
    
    const roundId = Math.max(...messages.value.map(m => m._round), 0) + 1
    
    // 重置重试计数和记录开始时间
    let retryCount = 0
    const startTime = Date.now()
    
    // 生成 contentIndex：优先使用传递的 contentIndex，其次按原有逻辑生成
    let contentIndex: number
    if (params.contentIndex !== undefined) {
      // 如果明确传递了 contentIndex，则使用它
      contentIndex = params.contentIndex
    } else if (params.skipContentIndexGeneration && messages.value.length > 0) {
      // 如果 skipContentIndexGeneration 为 true，使用最后一条消息的 contentIndex
      contentIndex = messages.value[messages.value.length - 1].contentIndex || 1
    } else {
      // 否则按原有逻辑生成新的 contentIndex
      const maxContentIndex = messages.value.length > 0 
        ? Math.max(...messages.value.map(m => m.contentIndex || 0), 0)
        : 0
      contentIndex = maxContentIndex + 1
    }
    
    // 只有在不是编辑消息的情况下才添加用户消息
    if (!params.isEdit) {
      addMessage({
        text: params.message,
        sender: 'user',
        _round: roundId,
        imageList: params.images,
        createTime: new Date().toISOString(),
        contentIndex: contentIndex
      })
    }
    
    // 添加AI消息占位
    const aiMsgIndex = addMessage({
      text: '',
      sender: 'assistant',
      thinking: true,
      thinkingText: '处理中...',
      _round: roundId,
      isStreaming: true,
      modelName: String(params.model),
      status: 'before',
      createTime: new Date().toISOString(),
      contentIndex: contentIndex + 1
    })
    
    currentStreamId.value = ++globalStreamId.value
    abortController.value = new AbortController()
    
    callbacks?.onStart?.()
    
    try {
      // 导入aiService
      const { aiService } = await import('../../shared/services/ai-service')
      
      // 准备请求参数
      const requestParams = {
        userId: userStore.userId || 0,
        sessionId: userStore.sessionId,
        content: params.message,
        modelId: params.model || undefined,
        temperature: undefined,
        maxTokens: undefined,
        topP: undefined,
        memory: params.memoryEnabled,
        knowledgeId: params.knowledgeId ? Number(params.knowledgeId) : undefined,
        useTools: params.useTools,
        contentIndex: contentIndex,
        systemPromptId: params.systemPromptId
      }
      
      console.log(`流式连接已建立 - 会话ID: ${userStore.sessionId || '未指定'}`)
      
      // 触发打开回调
      callbacks?.onOpen?.()
      
      // 使用统一的streamChat方法
      await aiService.streamChat(requestParams, {
        onMessage: (data) => {
          if (data.event === 'message') {
            // 处理每个文本块
            try {
              const newText = data.data
              
              // 更新消息内容
              updateMessage(aiMsgIndex, {
                thinking: false,
                text: newText,
                status: 'running'
              })
              
              callbacks?.onProgress?.(newText, 'running')
            } catch (e) {
              console.error('处理流数据失败:', e);
            }
          }
        },
        onError: (error) => {
          // 记录错误发生时间
          const errorTime = Date.now()
          const timeSinceStart = errorTime - startTime
          
          // 更新消息状态为错误
          updateMessage(aiMsgIndex, {
            isStreaming: false,
            status: 'error',
            text: '连接中断，请稍后重试'
          })
          
          // 重置状态
          isStreaming.value = false
          aiState.value = 'idle'
          abortController.value = null
          
          // 智能重试判断
          if (timeSinceStart < 5000 && retryCount < 2) {
            // 如果在5秒内出错且重试次数少于2次，允许重试
            console.log(`连接早期失败，尝试重试 ${retryCount + 1}/2`)
            retryCount++
            // 递归调用重试
            sendStreamMessage(params, callbacks)
          } else {
            // 否则停止重试
            console.log('连接失败时间过长或重试次数过多，停止重试')
            // 触发错误回调
            callbacks?.onError?.(error)
          }
        },
        onComplete: () => {
          // 流结束
          if (currentStreamId.value === globalStreamId.value) {
            updateMessage(aiMsgIndex, {
              isStreaming: false,
              status: 'completed',
              thinking: false
            })
            isStreaming.value = false
            aiState.value = 'idle'
            abortController.value = null
            callbacks?.onComplete?.()
          }
        }
      })
    } catch (error) {
      // 忽略主动中止的错误
      if (error instanceof Error && error.name === 'AbortError') return
      
      // 其他错误已经在 streamChat 的 onError 回调中处理
    }
  }
  
  const abortStream = () => {
    if (abortController.value) {
      abortController.value.abort()
      abortController.value = null
    }
    
    isStreaming.value = false
    aiState.value = 'idle'
    
    // 更新正在流式传输的消息状态
    const streamingMsgIndex = messages.value.findIndex(msg => msg.isStreaming)
    if (streamingMsgIndex !== -1) {
      const currentText = messages.value[streamingMsgIndex]?.text || ''
      updateMessage(streamingMsgIndex, {
        isStreaming: false,
        status: 'completed',
        text: hasMeaningfulContent(currentText) ? currentText : '已终止'
      })
    }
    
    currentStreamId.value = ++globalStreamId.value
  }
  
  // 添加连接状态监控
  const checkConnectionHealth = () => {
    if (isStreaming.value && !abortController.value) {
      console.warn('检测到异常连接状态，正在清理...');
      abortStream()
    }
  }
  
  // 定期清理异常连接（每30秒检查一次）
  let connectionHealthCheck: number | null = null
  
  const startConnectionHealthCheck = () => {
    if (connectionHealthCheck) {
      clearInterval(connectionHealthCheck)
    }
    connectionHealthCheck = window.setInterval(checkConnectionHealth, 30000)
  }
  
  const stopConnectionHealthCheck = () => {
    if (connectionHealthCheck) {
      clearInterval(connectionHealthCheck)
      connectionHealthCheck = null
    }
  }
  
  // 在组件卸载时清理
  if (typeof window !== 'undefined') {
    window.addEventListener('beforeunload', () => {
      if (isStreaming.value) {
        abortStream()
      }
      stopConnectionHealthCheck()
    })
  }
  
  return {
    messages,
    isStreaming,
    thinkingMessages,
    showThinking,
    thinkingContent,
    aiState,
    sendStreamMessage,
    abortStream,
    startConnectionHealthCheck,
    stopConnectionHealthCheck
  }
}